import { defineStore } from 'pinia'
import { ref } from 'vue'
import defaultAvatar from '@/assets/default.png'

export const useUserInfoStore = defineStore('userInfo', () => {
  // 初始状态从localStorage读取
  // JSON.parse(localStorage.getItem('userInfo')) || 
  const initialState = JSON.parse(localStorage.getItem('userInfo')) || {
    id: '',
    username: '',
    avatar: '',
    email: '',
    mobile: '',
    realName: '',
    gender: '',
    birthday: '',
    address: '',
    token: '', // 关键信息：保留Token
    identity: '', // 保留身份信息
    isLoggedIn: false
  }

  const userInfo = ref(initialState)

  // 登录：覆盖完整信息
  const login = (loginResponse) => {
    userInfo.value = {
      ...initialState,
      ...loginResponse,
      isLoggedIn: true,
      avatar: loginResponse.avatar || defaultAvatar
    }
    console.log(userInfo)
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  // 登出：重置状态
  const logout = () => {
    userInfo.value = {
      ...initialState,
      isLoggedIn: false,
      token: '' // 清空Token
    }
    localStorage.removeItem('userInfo')
  }

  // 更新用户信息：只更新需要的字段，保留Token等关键信息
  const updateUserInfo = (newInfo) => {
    userInfo.value = {
      ...userInfo.value,
      ...newInfo,
      token: userInfo.value.token,
      identity: userInfo.value.identity,
      isLoggedIn: true
    }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }


  const setUserInfo = (newInfo) => {
    userInfo.value = {
      ...userInfo.value,
      ...newInfo
    }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  return {
    userInfo,
    login,
    logout,
    updateUserInfo,
    setUserInfo
  }
})